<?php

namespace app\api\controller;

use app\api\exception\ApiServiceException;
use app\common\model\Goods;
use app\common\model\GoodsSku;
use app\common\service\TimeService;
use think\response\Json;

class TimeController extends ApiBaseController
{
    public array $loginExcept = [
        'api/time/getGoodsList',
        'api/time/test',
        'api/time/updateStock',
        'api/time/index',
    ];
    protected $service;

    public function __construct()
    {
        $this->service = new TimeService('93VGNQRG5MYBU0', 'l07g8r45m89xkak0', 'qb82jd75anjxdxka', 'https://main.miniappss.com');
    }


    //定时任务商品信息写入本地数据库
    public function getGoodsList(): Json
    {
        $time = time();
        $page = session('page') ?? 0; // 从 session 中获取上一次请求的页码，默认为 0
        $pageSize = 50; // 每页数据条数
        // 获取总数据条数
        $totalData = $this->service->fetchGoodsList(0, 1); // 只请求第一页，且只返回总数
        $total = $totalData['total'];
        // 计算总页数
        $pageCount = ceil($total / $pageSize);
        // 根据当前页码获取数据
        $data = $this->service->fetchGoodsList($page, $pageSize);
        foreach ($data['goods_list'] as $goods) {
            // 查询数据库中是否已存在相同 SKU 的商品
            $existingGoods = Goods::where('sku', $goods['sku'])->find();
            if (!$existingGoods) {
                $insertData = [
                    'sku' => $goods['sku'],
                    'library' => $goods['library'],
                    'stock' => $goods['stock'],
                    'shop_price' => $goods['shop_price'],
                    'main_image' => $goods['main_image'],
                    'title' => $goods['title'],
                    'create_time' => $time,
                    'update_time' => $time,
                ];
                $goods_id = Goods::insertGetId($insertData);
                if ($goods_id) {
                    foreach ($goods['variety'] as $index => $variety) {
                        // 从对应位置获取对应的 variety_price 数据
                        $varietyPrice = $goods['variety_price'][$index];
                        $varietyData = [
                            'goods_id' => $goods_id,
                            'sku' => $goods['sku'],
                            'sku_id' => $variety['id'],
                            'title' => $variety['title'],
                            'value' => $variety['value'],
                            'url' => $variety['url'],
                            'shop_price' => $varietyPrice['shop_price'], // 获取对应的 shop_price
                            'created_time' => $time,
                            'updated_time' => $time,
                        ];
                        GoodsSku::insert($varietyData);
                    }

                }
            }
        }
        // 批量插入数据
        // 更新 session 中的页码
        $page = ($page + 1) % $pageCount; // 如果当前页码已经到达最大值，则重新从第一页开始
        session('page', $page);
        // 返回插入的记录数
        return api_success();

    }

    //定时任务更新商品库存
    public function updateStock(): Json
    {
        $time = time();
        $goodsList = Goods::order('update_time desc')->limit(50)->select();
        foreach ($goodsList as $goods) {
            $goodsInfo = $this->service->fetchGoodsInfo((int)$goods['sku'], (int)$goods['library']);
            if ($goodsInfo) {
                $updateData = [
                    'sku' => $goodsInfo['sku'],
                    'library' => $goodsInfo['library'],
                    'stock' => $goodsInfo['stock'],
                    'shop_price' => $goodsInfo['shop_price'],
                    'main_image' => $goodsInfo['main_image'],
                    'title' => $goodsInfo['title'],
                    'update_time' => $time,
                    'content' => json_encode($goodsInfo['content'])
                ];
                $result = Goods::where('id', $goods['id'])->update($updateData);
                if ($result) {
                    foreach ($goodsInfo['variety'] as $index => $variety) {
                        // 从对应位置获取对应的 variety_price 数据
                        $varietyPrice = $goods['variety_price'][$index];
                        $sku_find = GoodsSku::where([
                            'sku_id' => $variety['id'],
                            'goods_id' => $goods['id'],
                            'sku' => $goods['sku'],
                        ])->find();
                        if ($sku_find) {
                            $varietyData = [
                                'goods_id' => $goods['id'],
                                'sku_id' => $variety['id'],
                                'sku' => $goodsInfo['sku'],
                                'title' => $goodsInfo['title'],
                                'value' => $goodsInfo['value'],
                                'url' => $variety['url'],
                                'shop_price' => $varietyPrice['shop_price'], // 获取对应的 shop_price
                                'update_time' => $time,
                            ];
                            GoodsSku::where('id', $sku_find['id'])->update($varietyData);
                        } else {
                            $varietyData = [
                                'goods_id' => $goods['id'],
                                'sku_id' => $variety['id'],
                                'sku' => $goodsInfo['sku'],
                                'title' => $goodsInfo['title'],
                                'value' => $goodsInfo['value'],
                                'url' => $variety['url'],
                                'shop_price' => $varietyPrice['shop_price'], // 获取对应的 shop_price
                                'create_time' => $time,
                                'update_time' => $time,
                            ];
                            GoodsSku::insert($varietyData);
                        }
                    }

                }
            }
        }
        return api_success();
    }

}